using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;
using Barbar.MapReport.HtmlRender.Handlers;

namespace Barbar.MapReport.HtmlRender.Shapes {
  internal class ShapeHandler : ISimpleHttpHandler {
    public static HandlerUrl GetURL(IShape shape) {
      if (shape == null)
        throw new ArgumentNullException("shape");
      HandlerUrl handlerUrl = new HandlerUrl(typeof(ShapeHandler));
      handlerUrl.AddParameter("shape", shape.Serialize());
      handlerUrl.AddParameter("typeName", HttpUtility.UrlEncode(shape.GetType().FullName));
      return handlerUrl;
    }

    #region ISimpleHttpHandler Members

    public void ProcessRequest(HttpContext context) {
      HttpRequest request = context.Request;
      string typeName = request["typeName"];
      IShape shape = Shape.Deserialize(request["shape"], Type.GetType(typeName));
      
      Bitmap bitmap = new Bitmap(shape.Width, shape.Height);
      using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap)) {
        graphics.SmoothingMode = SmoothingMode.AntiAlias;
        shape.Draw(graphics);
        graphics.Flush(System.Drawing.Drawing2D.FlushIntention.Sync);
      }
      
      byte[] buffer;
      using (MemoryStream stream = new MemoryStream()) {
        bitmap.Save(stream, ImageFormat.Png);
        stream.Close();
        buffer = stream.GetBuffer();
      }

      context.Response.Cache.SetCacheability(HttpCacheability.Public);
      context.Response.Cache.VaryByParams.IgnoreParams = false;
      context.Response.Cache.SetMaxAge(TimeSpan.FromDays(1));

      context.Response.ContentType = "image/png";
      context.Response.BinaryWrite(buffer);
    }

    #endregion
  }
}
